package com.im.immodel.config

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import com.alibaba.android.arouter.launcher.ARouter
import com.hotpot.core.Hotpot
import com.hotpot.sdk.config.HandlerConfig.unReadTimelineId
import com.hotpot.sdk.room.entity.receive.SessionListReceive
import com.hotpot.sdk.utils.*
import com.hotpot.uikit.talk.MessageListFragment
import com.hotpot.uikit.talk.TalkingHostActivity
import com.hotpot.uikit.talk.config.listener.MessageListProxy
import com.hotpot.uikit.talk.entity.SessionRemovePayLoadEntity
import com.hotpot.uikit.talk.entity.TalkingTopEntity
import com.hotpot.uikit.talk.groupreview.GroupReviewActivity
import com.hotpot.uikit.talk.model.TalkingListViewModel
import com.hotpot.uikit.talk.talkingnewmember.TalkingNewMemberActivity
import com.hotpot.uikit.utils.IMVoiceOrVideoManager
import com.hotpot.uikit.utils.hotpothandler.HotpotActionHandler
import com.hotpot.uikit.view.pop.NoticeDialog
import com.hotpot.uikit.view.pop.NoticeDialogListener
import com.im.immodel.R
import com.lxj.xpopup.XPopup
import com.qgb.zcore.mmkvutil.CacheMarker
import com.qgb.zcore.mmkvutil.MkvUtils
import com.qgb.zcore.router.ContactsRouterPath
import com.qgb.zcore.router.RouteHelper.navigateTo
import com.qgb.zutils.ThreadUtils
import com.qgb.zutils.LogUtils.Forest.d


class IMListConfigPresenter : MessageListProxy {

    var viewModel: TalkingListViewModel? = null
    var mContext: MessageListFragment? = null
    var launchForesult: ActivityResultLauncher<Intent>? = null

    override fun onInitData(
            viewModel: TalkingListViewModel,
            mContext: MessageListFragment,
            launchForesult: ActivityResultLauncher<Intent>
    ) {
        this.viewModel = viewModel
        this.mContext = mContext
        this.launchForesult = launchForesult
    }

    override fun onItemClick(view: View?, sessionListReceive: SessionListReceive?, postion: Int) {
        d("Talking", "getType=" + sessionListReceive!!.type)
        val unReadSessionId = sessionListReceive!!.timelineId
        //群解散
        if (sessionListReceive!!.dissolveState != null && sessionListReceive!!.dissolveState == 1) {
            removeGroupChatNotification(unReadSessionId, "2")
            return
        }
        // 此会话已经被删除 点击确认移除
        if (sessionListReceive!!.status != null && sessionListReceive!!.status!!) {
            removeGroupChatNotification(unReadSessionId, "1")
            return
        }
        if (TextUtils.equals(SINGLE, sessionListReceive!!.type)) { //单聊
            if (TextUtils.equals(SYS_ROBOT_NEW_FRIEND, sessionListReceive!!.userId)) { //新的好友
                viewModel?.sendReadMsg(sessionListReceive)
                navigateTo(ContactsRouterPath.applyFriendList)
                return
            } else if (TextUtils.equals(SYS_ROBOT_GROUP_APPLY, sessionListReceive!!.userId)) { //群成员加入审核
                viewModel?.sendReadMsg(sessionListReceive)
                GroupReviewActivity.start(mContext!!.requireActivity())
                return
            } else if (TextUtils.equals(SYS_ROBOT_MEMBER_APPLY, sessionListReceive!!.userId)) { //新成员申请
                viewModel?.sendReadMsg(sessionListReceive)
                TalkingNewMemberActivity.start(mContext!!.requireActivity(), sessionListReceive!!)
                return
            }
        }
        //跳转工作通知详情页
//                if (WORK_NOTIFY.equals(sessionListReceive.getGroupType())) {
//                    goWorkNoticeDetails(sessionListReceive);
//                    return;
//                }
        //通知列表界面
        //跳转工作通知详情页
//                if (WORK_NOTIFY.equals(sessionListReceive.getGroupType())) {
//                    goWorkNoticeDetails(sessionListReceive);
//                    return;
//                }
        //通知列表界面
        if (TextUtils.equals(IM_SYSTEM_ACCOUNT_TOTAL, sessionListReceive!!.userId)) {
            viewModel?.sendReadMsg(sessionListReceive)
            //MultipleNoticeActivity.start(mContext!!.requireActivity(), sessionListReceive!!)
            ARouter.getInstance()
                    .build("/jyb_im/news_notice")
                    .navigation();
            return
        }
        goSessionDetails(sessionListReceive, unReadSessionId)
    }

    override fun onItemSetting(view: View?, sessionListReceive: SessionListReceive?, postion: Int) {
        //跳转到栈
        val bundle = Bundle()
        bundle.putSerializable("SESSIONLISTRECEIVE", sessionListReceive)
        bundle.putBoolean("FROMLIST", true)
        bundle.putString("IMACCOUNT", MkvUtils.get().getString(MkvUtils.UserData, CacheMarker.ImAccount, ""))
        mContext!!.startNavActivity(R.navigation.hpui_nav_setting, bundle)
    }

    override fun onItemBtnTop(view: View?, sessionListReceive: SessionListReceive?, postion: Int) {
        var toAccount: String? = ""
        if (TextUtils.equals(SINGLE, sessionListReceive!!.type)) {
            toAccount = sessionListReceive!!.userId
        } else if (TextUtils.equals(GROUP, sessionListReceive!!.type)) {  //群聊
            toAccount = sessionListReceive!!.timelineId
        }
        val topEntity = TalkingTopEntity()
        topEntity.setisTop(!sessionListReceive!!.top!!)
        topEntity.type = sessionListReceive!!.type

        sessionListReceive!!.top = !sessionListReceive!!.top!!
        //发送置顶消息
        //发送置顶消息
        val content = Commands.getInstance().makeTalkingListSessionSetTop(viewModel!!.account, toAccount, topEntity)
        Hotpot.Companion.instance.strongSend(content)

        ThreadUtils.runOnSubThread {
            RoomDaoHelper.Companion.instaner.sessionListDao!!.updateSession(sessionListReceive)
            RoomDaoHelper.Companion.instaner.sessionListDao!!.listTopSession()
        }
    }

    override fun onItemBtnDelete(view: View?, sessionListReceive: SessionListReceive?, postion: Int) {
        var toAccount: String? = ""
        if (TextUtils.equals(SINGLE, sessionListReceive!!.type)) {
            toAccount = sessionListReceive!!.userId
        } else if (TextUtils.equals(GROUP, sessionListReceive!!.type)) {  //群聊
            toAccount = sessionListReceive!!.timelineId
        }
        val removePayLoadEntity = SessionRemovePayLoadEntity()
        removePayLoadEntity.type = sessionListReceive!!.type
        removePayLoadEntity.isIsRemove = true
        //发送移除会话
        //发送移除会话
        val content =
                Commands.getInstance().makeTalkingListSessionRemove(viewModel!!.account, toAccount, removePayLoadEntity)
        Hotpot.Companion.instance.strongSend(content)
        ThreadUtils.runOnSubThread {
            RoomDaoHelper.Companion.instaner.sessionListDao!!.deleteSession(sessionListReceive)
            RoomDaoHelper.Companion.instaner.sessionListDao!!.listTopSession()
            viewModel!!.clearMsgCache(sessionListReceive)
        }
    }

    override fun onItemBtnMeeting(view: View?, sessionListReceive: SessionListReceive?, postion: Int) {
        IMVoiceOrVideoManager.getInstance().isSingleChat = false
        IMVoiceOrVideoManager.getInstance().setSessionListReceive(sessionListReceive)
        HotpotActionHandler.instance.callMeeting(mContext!!.requireActivity(),sessionListReceive!!.timelineId, sessionListReceive!!.name!!)
    }

    override fun onItemBtnVoice(view: View?, sessionListReceive: SessionListReceive?, postion: Int) {
        IMVoiceOrVideoManager.getInstance().isSingleChat = true
        IMVoiceOrVideoManager.getInstance().setSessionListReceive(sessionListReceive)
        HotpotActionHandler.instance.callAudio(mContext!!.requireActivity(),
                sessionListReceive!!.userId!!, sessionListReceive.userNo!!,
                sessionListReceive.imgAvator!!, sessionListReceive.name!!
        )
    }

    override fun onItemBtnVideo(view: View?, sessionListReceive: SessionListReceive?, postion: Int) {
        IMVoiceOrVideoManager.getInstance().isSingleChat = true
        IMVoiceOrVideoManager.getInstance().setSessionListReceive(sessionListReceive)
        HotpotActionHandler.instance.callVideo(mContext!!.requireActivity(),
                sessionListReceive!!.userId!!, sessionListReceive.userNo!!,
                sessionListReceive.imgAvator!!, sessionListReceive.name!!)
    }


    private fun goSessionDetails(sessionListReceive: SessionListReceive, unReadSessionId: String) {
        val intent = Intent()
        intent.putExtra(TalkingHostActivity.EXTRA_DATA, sessionListReceive)
        intent.setClass(mContext!!.requireActivity(), TalkingHostActivity::class.java)
        launchForesult?.launch(intent)
        unReadTimelineId = unReadSessionId
    }

    private var noticeDialog: NoticeDialog? = null

    /**
     * 被移除群聊后 收到的通知弹窗
     */
    private fun removeGroupChatNotification(timelineId: String, type: String) {
        if (noticeDialog != null) {
            return
        }
        noticeDialog = XPopup.Builder(mContext!!.requireActivity())
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .autoDismiss(true)
                .isDestroyOnDismiss(true)
                .asCustom(NoticeDialog(mContext!!.requireActivity())) as NoticeDialog
        if (TextUtils.equals(type, "1")) { // 被移除
            noticeDialog!!.content = mContext!!.getString(R.string.hpui_you_were_removed_from_the_group_chat_str)
        } else if (TextUtils.equals(type, "2")) { //被解散
            noticeDialog!!.content = mContext!!.getString(R.string.hpui_the_group_chat_has_been_disbanded_str)
        } else if (TextUtils.equals(type, "3")) { //未在群中
            noticeDialog!!.content = mContext!!.getString(R.string.hpui_you_are_no_longer_group_chat)
        }
        noticeDialog!!.confirm = mContext!!.getString(R.string.hpui_text_i_known)
        noticeDialog!!.noticeDialogListener = object : NoticeDialogListener {
            override fun onIKnow() {
                noticeDialog = null
                if (TextUtils.equals(type, "3")) {
                    return
                }
                viewModel!!.delReadyRemove(timelineId)
            }
        }
        noticeDialog!!.show()
    }
}